import { createRouter, createWebHistory } from 'vue-router'
import AuthView from '../views/page/AuthView.vue'
import LoginView from '@/views/user/account/LoginView.vue'
import RegisterView from '@/views/user/account/RegisterView.vue'
import MainView from '@/views/page/MainView.vue'
import NotFound from '@/views/error/NotFound.vue'
import SettingView from '@/views/page/SettingView.vue'
import MyselfView from '@/views/me/MyselfView.vue'
import PkindexView from '@/views/game/pk/mul/PkindexView.vue'
import SinglePkView from '@/views/game/pk/single/SinglePkView.vue'

import { useUserStore } from '@/store/user'
import ChatWindow from '@/views/me/chat/ChatWindow.vue'
import FriendRelation from '@/views/me/about/FriendRelation.vue'

const routes = [
    {
        path: '/',
        name: 'home',
        redirect: '/auth/',
        meta: {
            requestAuth: true, // 需要登录
        },
    },
    {
        path: '/main/friends/',
        name: 'test',
        component: FriendRelation,
        meta: {
            requestAuth: true, // 需要登录
        },
    },

    {
        path: '/auth/',
        name: 'auth',
        component: AuthView,
        meta: {
            requestAuth: false, // 需要登录
        },
    },
    {
        path: '/user/account/login/',
        component: LoginView,
        name: 'login',
        meta: {
            requestAuth: false,
        },
    },
    {
        path: '/user/account/register/',
        component: RegisterView,
        name: 'register',
        meta: {
            requestAuth: false,
        },
    },
    {
        path: '/main/',
        name: 'main',
        component: MainView,
        meta: {
            requiresAuth: true,
        },
    },
    {
        path: '/me/chat/',
        name: 'chat',
        component: ChatWindow,
        meta: {
            requiresAuth: true,
        },
    },
    {
        path: '/main/singlepk/pk',
        name: 'pk',
        component: SinglePkView,
        meta: {
            requiresAuth: true,
        },
    },
    {
        path: '/main/multipk/',
        name: 'multipk',
        component: PkindexView,
        meta: {
            requiresAuth: true,
        },
    },

    {
        path: '/setting/',
        name: 'setting',
        component: SettingView,
        meta: {
            requiresAuth: true,
        },
    },
    {
        path: '/me/myself/',
        name: 'me',
        component: MyselfView,
        meta: {
            requiresAuth: true,
        },
    },

    {
        path: '/404/',
        name: 'notfound',
        component: NotFound,
    },
    {
        path: '/:catchAll(.*)',
        redirect: '/404/',
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    const store = useUserStore()
    // 路由守卫，检查用户是否登录
    if (to.meta.requestAuth && !store.is_login) {
        next({ name: 'login' })
    } else {
        next() // 确保一定要调用 next()
    }
})

export default router
